<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>屏保待机效果</title>
    <script type="text/javascript" src="/Public/js/jquery-1.11.2.min.js"></script>
    <style>
        div
        {
            position:absolute;
            width:100px;
            height:100px;
            background:green;
            border-radius:50%;
            line-height:100px;
            text-align:center;
        }
    </style>
</head>
<body>
    <div id="did">屏保</div>
    <script>
    //全局变量
    var xStep = 2; //横向步进
    var yStep = 3; //纵向步进
    var inte = null;

    //入口
    run();
    function run(){
        //设置定时器
        inte = setInterval(function()
            {
                //获取div
                var div =$('div');
                //获取div的left 和 top
                var divl = div.offset().left;
                var divt = div.offset().top;
                //计算新的left和top
                var newL = divl + xStep;
                var newT = divt + yStep;
                //获取窗口的宽和高
                var ww = $(window).width();
                var wh = $(window).height();

                //获取div的宽和高
                var divw = div.width();
                var divh = div.height();

                //计算最大的left top
                var maxL = ww - divw - 3;
                var maxT = wh - divh - 3;
                //检测
                if(newL > maxL || newL < 0)
                {
                    xStep = -xStep;
                    div.css('background',randColor());
                }
                if(newT > maxT || newT < 0)
                {
                    yStep = -yStep;
                    div.css('background',randColor());
                }

                div.css('left',newL +'px');
                div.css('top',newT + 'px');
            },10);
    }

    $('div').on('mouseover',function(){
        clearInterval(inte);
    });

    $('div').on('mouseout',function(){
        run();
    });

    //随机颜色
    function randColor()
    {
         var r = rand(0,255);
         var g = rand(0,255);
         var b = rand(0,255);
         return "rgb(" + r + ',' + g + ',' + b + ")";
    }

    //随机函数
    function rand(m,n)
        {
            return Math.ceil(Math.random()*(n-m+1))+m-1;
        }
    </script>
</body>
</html>